<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
    <el-form-item label="课程编号">
            <el-input v-model="listQuery.fcourseno" clearable class="filter-item" style="width: 200px;" placeholder="请输入课程编号"/>
      </el-form-item>
      <el-form-item label="课程名称">
            <el-input v-model="listQuery.fcoursename" clearable class="filter-item" style="width: 200px;" placeholder="请输入课程名称"/>
      </el-form-item>
      <el-form-item>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" @click="handleFilter">查找</el-button>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.add ,color:buttonColor.color}" @click="handleCreate">添加</el-button>
        <el-button round size="medium" :style="{background:buttonColor.import,color:buttonColor.color}" @click="handleUpload">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table :height="buttonColor.clientHeight" v-loading="listLoading" :data="list" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
           <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
            <img src="../../../public/images/edit.png" />
            编辑
          </div>
          <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
            <img src="../../../public/images/del.png" />
            删除
          </div>
          </div>
        </template>
      </el-table-column>
     <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column :width="buttonColor.billno" align="center" label="课程编号" prop="fcourseno" />
      <el-table-column :width="buttonColor.name" align="left" label="课程名称" prop="fcoursename" />
      <el-table-column align="left" label="描述" prop="fnote" />
      <el-table-column align="left" :width="buttonColor.state" label="课程状态" prop="fstate">
        <template slot-scope="scope">
          <span :style="{color:buttonColor.statedisable}" v-if="scope.row.fstate==0">{{ scope.row.fstate | statusFilter }}</span>
          <span :style="{color:buttonColor.statestart}" v-else>{{ scope.row.fstate | statusFilter }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible"  width="450px">
    <template slot="title">
      <div :style="titleColor">{{textMap[dialogStatus]}}</div>
    </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="margin:0 50px;">
       <el-form-item class="required" label="课程编号" prop="fcourseno">
          <el-input v-if="dialogStatus === 'create'" v-model="dataForm.fcourseno"/>
          <el-input v-else disabled v-model="dataForm.fcourseno"/>
        </el-form-item>
       <el-form-item class="required" label="课程名称" prop="fcoursename">
          <el-input v-model="dataForm.fcoursename"/>
        </el-form-item>
        <el-form-item label="描述" prop="fnote">
          <el-input v-model="dataForm.fnote"/>
        </el-form-item>
        <el-form-item class="el-form-item-small" label="课程状态" prop="fstate">
          <el-select v-model="dataForm.fstate" class="filter-item" placeholder="请选择课程状态">
            <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
        <el-button round v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 导出弹窗 -->
    <el-dialog width="auto" :close-on-click-modal="false" :visible.sync="uploadVisible">
       <template slot="title">
      <div :style="exportColor">课程表</div>
    </template>
      <div style="width:300px;height:200px;display: flex;flex-direction: column;align-items: center">
          <el-upload
          :on-success="uploadFileSuccess"
          :headers="headers"
          :action="uploadPath2"
          :data="{'tableName':'import_i_ts_tsCourse'}"
          :show-file-list="false"
          class="filter-item"
          style="margin-top:20px"
          accept=".xlsx">
          <el-button round size="medium" icon="el-icon-upload" :style="{background:buttonColor.import,color:buttonColor.color}">导入</el-button>
        </el-upload>
        <div style="margin-top:30px;text-decoration:underline">
          <a :href="downUrl" style="color: blue">模板文件下载</a>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .button-margin {
    margin : 2px 0px;
  }
  .el-button+.el-button {
    margin-left: 1px;
  }
</style>

<script>
import { listtsCourse, createtsCourse, updatetsCourse, deletetsCourse } from '@/api/tsCourse'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { uploadPath2 } from "@/api/area"
import { getToken } from '@/utils/auth'
import { getApiUrl } from '@/utils/request'
import { tableColor,titleColor,buttonColor,exportColor } from '@/filters/index'

const statusMap = {
  0: '禁用',
  1: '启用'
}

export default {
  name: 'STsCourse',
  components: { Pagination },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      statusMap,
      downUrl: null,
      uploadVisible: false,
      exportColor,
      buttonColor,
      titleColor,
      tableColor,
      getApiUrl,
      getToken,
      uploadPath2,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fcourseno: undefined,
        fcoursename: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fcourseno: undefined,
        fcoursename: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fcourseno: [
          { required: true, message: '课程编号不能为空' },
        ],
        fcoursename: [
          { required: true, message: '课程名称不能为空' },
        ],
      }
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  created() {
    this.downUrl = getApiUrl() + 'xlsx/1-7实验楼.xlsx'
    this.getList()
  },
  methods: {
    // 导入
     uploadFileSuccess: function(response) {
       this.uploadVisible = false
      this.$notify.success({
        title: '导入',
        dangerouslyUseHTMLString:true,
        message: response.data
      })
    },
    handleUpload(){
      this.uploadVisible = true
    },
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    getList() {
      this.listLoading = true
      console.log('this.listQuery.fcourseno',this.listQuery.fcourseno)
      if(!this.listQuery.fcourseno){
        this.listQuery.fcourseno = null
      }
      listtsCourse(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fcourseno: undefined,
        fcoursename: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.fstate = '1'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          createtsCourse(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加课程表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
       this.dataForm.fstate = row.fstate.toString()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
           this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          updatetsCourse(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fcourseno === this.dataForm.fcourseno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新课程表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除此课程表', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletetsCourse(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除课程表成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
